package com.tianqu.tms.core.base;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ResourceBundle;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import com.tianqu.tms.core.exception.ConnectionException;
import com.tianqu.tms.core.util.Registry;
import com.tianqu.tms.core.util.TmsConstants;

/**
 * 
 * @author liugang
 *
 */
public class ConnectionFactoryImpl extends ConnectionFactory implements TmsConstants {

	private Logger logger = Logger.getLogger(ConnectionFactoryImpl.class);
	private String dataSourceName = null;
	private DataSource ds=null;
	
	/**
	 * 
	 */
	public ConnectionFactoryImpl()  {
		ResourceBundle rb = (ResourceBundle)Registry.get(PROPERTIES);
		dataSourceName = rb.getString(DATASOURCE_NAME);
	}
	private DataSource getDS() throws NamingException{
		if( ds != null ){ return ds; }
		Context ctx = new InitialContext();
		ds = (DataSource)ctx.lookup("java:comp/env/jdbc/"+dataSourceName);
		return ds;
	}
	/**
	 * @return Connection
	 *
	 */
	public Connection getConnection() throws ConnectionException {
			Connection conn = null;
		try{
			conn =getDS().getConnection();
			conn.setAutoCommit(true);
		}catch(NamingException e){
			logger.debug("failed to get DataSource: " + dataSourceName, e);
			throw new ConnectionException("failed to lookup ds: " + dataSourceName, e);
		}catch(SQLException e){
			logger.debug("failed to get connection",e);
			throw new ConnectionException("failed to get connection " + e, e);
		}
		return conn;
	}
}
